<template>
  <div style="height: 100%;">
    <div v-if="datasetCategory.length === 0" class="div-empty">
      <div>
        <img alt="" src="@/assets/view/category-empty.svg" />
        <div>暂无数据</div>
        <div>请先创建分类~</div>
      </div>
    </div>
    <div v-else class="dataset">
      <a-tree
        :selected-keys="selectedKeys"
        :tree-data="treeData"
        :draggable="hoveredDatasetId >= 0 && renamedId < 0"
        :show-icon="true"
        :expanded-keys="expandedKeys"
        @drop="onDrop"
        @select="onSelect"
      >
        <div slot="category" slot-scope="item">
          <div class="icon-pointer-containter" @click="clickCategory(item.id)">
            <a-icon-font
              style="font-size: 16px;"
              :class="[
                'icon-pointer',
                {
                  'icon-pointer-open': expandedKeys.includes(
                    `category${item.id}`
                  ),
                },
              ]"
              type="iconicon-beifen-right"
            />
          </div>
          <div class="category-title" @click="clickCategory(item.id)">
            <a-tooltip>
              <template slot="title">
                {{ item.title }}
              </template>
              <span class="category-title-itemtitle">{{ item.title }}</span>
            </a-tooltip>
          </div>
        </div>
        <div
          v-if="item.type !== 'empty'"
          slot="dataset"
          slot-scope="item"
          class="dataset-title"
          @mouseenter="() => onMouseEnter(item.id)"
          @mouseleave="onMouseLeave"
        >
          <div :id="'dataset' + item.id">
            <transition name="table-name" appear>
              <a-icon-font type="iconshujubiao"
            /></transition>
            <a-tooltip>
              <template slot="title">
                {{ item.title }}
              </template>
              <transition name="table-name" appear>
                <span
                  class="ellipsis-title"
                  @dblclick.stop="onItemDblClick($event, item)"
                  >{{ item.title }}</span
                ></transition
              >
            </a-tooltip>
          </div>
        </div>
        <div v-else class="data-empty">
          <div>无数据表</div>
        </div>
      </a-tree>
    </div>
  </div>
</template>

<script lang="ts">
/**
 * sider of data management view
 * show all categories and datasets of current user
 * @author Huihua Lu
 */
import { Component, Vue, Prop } from 'vue-property-decorator'
import DataStore from '@/store/modules/data'
// import { Modal } from 'ant-design-vue'

interface TreeNode {
  title: string
  key: string
  id: number
  type?: string
  scopedSlots?: any
  children?: Array<TreeNode>
}

@Component
export default class DataSiderInSql extends Vue {
  private hoveredDatasetId: number = -1

  // 删除
  private deleteVisible: boolean = false
  private deletedId: number = -1
  private deletedType: string = ''

  // 重命名与新建目录
  private renamedKey: string = ''
  private renamedId: number = -1
  private newName: string = ''
  private forbidBlur: boolean = false
  public expandedKeys: any = []
  @Prop() public selectedKeys: any

  // 正在编辑的选项的id
  private editId: number = -1

  // 正在保存的ID
  private savingId: number = -1

  // 将表格绑定只拆分层 id关联的map 解决双击编辑表名称的bug
  public bindValueMap: any = {}

  // 新建/重命名input回车之后隐藏input，来触发blur方法
  private inputShow: boolean = true

  // hover的按钮
  private hoverButtonName: string = ''

  public async created(): Promise<void> {
    await DataStore.loadDatasetCategory()
  }

  private mounted() {
    const { categoryId, datasetId } = DataStore

    this.clickCategory(categoryId.slice(8)) //  截取id 数字

    this.$nextTick(() => {
      this.onSelect([datasetId])
    })

    // setTimeout(() => {
    //   (document.querySelector('.ant-tree-treenode-selected')as HTMLElement).scrollIntoView() // 触发滚动到制定的元素
    // }, 500)
  }

  private beforeDestroy() {
    if (this.expandedKeys.length > 0) {
      const { length } = this.expandedKeys
      DataStore.setCategoryId(this.expandedKeys[length - 1])
    }

    if (this.selectedKeys[0] !== '') {
      DataStore.setDatasetId(this.selectedKeys[0])
    }
  }

  public get treeData(): TreeNode[] {
    const treeDataResult: Array<TreeNode> = []
    if (DataStore.datasetCategory) {
      DataStore.datasetCategory.forEach((value, index, array) => {
        const category = array[array.length - index - 1]
        const childrenResult: Array<TreeNode> = []
        category.dataset.forEach((dataset) => {
          childrenResult.push({
            title: dataset.name,
            key: `dataset${dataset.id}`,
            id: dataset.id,
            type: dataset.type,
            scopedSlots: { title: 'dataset' },
          })
        })
        treeDataResult.push({
          title: category.categoryName,
          key: `category${category.categoryId}`,
          id: category.categoryId,
          children:
            childrenResult.length !== 0
              ? childrenResult
              : [
                  {
                    title: 'empty',
                    key: `empty-${index}`,
                    type: 'empty',
                    id: -404 - index,
                    scopedSlots: { title: 'dataset' },
                  },
                ],
          scopedSlots: { title: 'category' },
        })
      })
    }

    return treeDataResult
  }

  public get datasetCategory() {
    return DataStore.datasetCategory
  }

  /* 单个数据集操作 */
  public onMouseEnter(datasetId: number) {
    this.hoveredDatasetId = datasetId
  }

  public onMouseLeave() {
    this.hoveredDatasetId = -1
  }

  private isDblClick: boolean = false

  private isSaving: boolean = false

  /* 更改数据集目录 */
  public async onDrop(info: any) {
    const dragNodePos: Array<string> = info.dragNode.pos.split('-')
    const dragCategoryIndex: number = Number.parseInt(dragNodePos[1], 10)
    const dragDatasetIndex: number = Number.parseInt(dragNodePos[2], 10)

    const dropNodePos: Array<string> = info.node.pos.split('-')
    const dropCategoryIndex: number = Number.parseInt(dropNodePos[1], 10)

    if (dropCategoryIndex === dragCategoryIndex) {
      return
    }

    const dragChildren = this.treeData[dragCategoryIndex].children
    if (!dragChildren) {
      return
    }
    const draggedDatasetId = dragChildren[dragDatasetIndex].id
    const draggedDatasetName = dragChildren[dragDatasetIndex].title
    const droppedCategoryId = this.treeData[dropCategoryIndex].id

    await DataStore.updateDataset({
      description: '',
      id: draggedDatasetId,
      name: draggedDatasetName,
      categoryId: droppedCategoryId,
    })
  }

  public setHover(value: any) {
    // 设置hoverButtonName的值
    this.hoverButtonName = value
  }

  // 点击分类 展开/收起
  public clickCategory(id: string) {
    const categoryId: string = `category${id}`
    const index = this.expandedKeys.findIndex((v: any) => v === categoryId)
    if (index < 0) {
      this.expandedKeys.push(categoryId)
    } else {
      this.expandedKeys.splice(index, 1)
    }
  }

  /* 查看数据集 */
  public onSelect(selectedKey: any) {
    // 判断有有效数据
    if (!(selectedKey && selectedKey[0])) {
      return
    }
    // 不处理空白节点、树节点、重复点击
    if (
      selectedKey[0].includes('empty-') ||
      selectedKey[0].includes('category') ||
      selectedKey.length === 0
    ) {
      return
    }
    if (this.inputShow && this.renamedKey === selectedKey[0]) {
      return
    }
    // if(this.$route.path!=='/management/data')
    // this.$router.push('/management/data')
    // 记录查看数据集的历史记录
    const [selectedDatasetKey] = selectedKey
    if (!selectedDatasetKey) {
      return
    }
    const selectedDatasetId = Number.parseInt(selectedDatasetKey.slice(7), 10)
    DataStore.pushPreSelectedDataset({
      id: DataStore.selectedDatasetId,
      name: this.selectedKeys[0],
      type: '',
    })
    this.$emit('set-selected-keys', selectedKey)
    DataStore.setSelectedDatasetId(selectedDatasetId)
  }
}
</script>

<style lang="less" scoped>
@import '@/constants';
// 左侧栏宽度
/deep/ aside .ant-layout-sider {
  max-width: 180px !important;
}

// 左侧栏empty状态
.button-disabled {
  color: #222432;
  opacity: 0.3;
  padding-left: 24px;

  // 前面的icon
  .icon-button-prefix {
    margin-right: 4px;
    width: 14px;
  }
}

.div-empty {
  align-items: center;
  display: flex;
  height: 100%;
  justify-content: center;
  margin-top: -36px;
  overflow: hidden;
  text-align: center;
}

.dataset {
  bottom: 0;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  position: absolute;
  top: 0;
  width: 180px;

  &::-webkit-scrollbar {
    height: 6px;
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(144, 147, 153, 0.5);
    border-radius: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
    border-radius: 5px;
  }
}

// 左侧栏
/deep/ .ant-tree li .ant-tree-node-content-wrapper {
  border: 0;
  height: 44px;
  line-height: 44px;
  width: 180px;
}

.category-title {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding-left: 40px;
  padding-right: 5px;
  width: 200px;

  .category-title-itemtitle {
    overflow: hidden;
    text-overflow: ellipsis;
    width: 119px;
  }
}

// 箭头样式
.icon-pointer-containter {
  height: 44px;
  position: absolute;
  width: 42px;

  .icon-pointer {
    position: absolute;
    right: 8px;
    top: calc(50% - 8px);
    transition: transform 0.3s;
  }

  .icon-pointer-open {
    transform: rotate(90deg);
  }
}

/deep/ .dataset li .ant-tree-switcher {
  display: none;
}

// 数据集外框
/deep/ .ant-tree-child-tree.ant-tree-child-tree-open {
  padding: 0;
}

/deep/ [role='treeitem'] {
  padding: 0 !important;
}

.dataset-title {
  align-items: center;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding-left: 42px;

  div {
    align-items: center;
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
  }

  /deep/ .new-input .ant-input {
    margin-left: 0;
    margin-top: 11px;
    width: 153px;
  }

  /deep/ .input-clear {
    color: rgba(0, 0, 0, 0.65);
    margin-right: -7px;
    margin-top: 10px;
    z-index: 999;
  }
}

.ellipsis-title {
  display: inline-block;
  margin-left: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 119px;
}

/* 覆盖树形菜单条目后的悬浮下拉框的样式 */
.ant-tree li ul {
  padding: 0 !important;
}

.ant-dropdown-menu {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 0 8px 0 rgba(0, 0, 0, 0.15);
  width: 61px;
}

li .ant-dropdown-menu-item {
  padding: 8px;
}

ul .ant-tree-child-tree.ant-tree-child-tree-open {
  padding: 0;
}

// 侧边栏 无数据表 样式
.data-empty {
  color: #c6c6c6;
  cursor: default;
  margin-left: -5px;
  padding-left: 45px;
  transition-duration: 0.3s;
  width: 180px;

  &:hover {
    background-color: #fff;
  }
}

// 更多信息的图标
.icon-font {
  padding-top: 15px;
}

.icon-more-options {
  height: 14px;
  margin-top: 16px;
  width: 14px;
}

// 子栏目长度
/deep/ .ant-tree li ul li .ant-tree-node-content-wrapper {
  padding-right: 10px;
}

// 新增/重命名的输入框
/deep/ .new-input .ant-input {
  border-radius: 4px;
  height: 22px;
  margin-left: 41px;
  padding: 0 6px;
  width: 154px;
}

// 清除输入框内容的icon
.input-clear {
  color: rgba(0, 0, 0, 0.65);
  margin-right: 7px;
  z-index: 999;
}

ul li .ant-dropdown-menu-item:hover {
  color: @TEXT_HOVER_COLOR;
}

.table-name-enter {
  opacity: 0;
  transform: translateY(-44px);
}

.table-name-enter-active {
  transition: all 0.5s ease;
}
</style>
